package com.agrimall.servlet;

import com.agrimall.entity.User;
import com.agrimall.service.UserService;
import com.agrimall.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 统一登录Servlet - 处理客户端、商户、管理员的登录
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl();
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.getRequestDispatcher("/login.jsp").forward(request, response);
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String userTypeStr = request.getParameter("userType");
        
        if (username == null || password == null || userTypeStr == null) {
            request.setAttribute("error", "请填写完整信息");
            request.getRequestDispatcher("/login.jsp").forward(request, response);
            return;
        }
        
        try {
            Integer userType = Integer.parseInt(userTypeStr);
            
            // 先查询用户是否存在
            User user = userService.getUserByUsername(username);
            
            if (user == null) {
                request.setAttribute("error", "用户名或密码错误");
                request.getRequestDispatcher("/login.jsp").forward(request, response);
                return;
            }
            
            // 验证用户类型是否匹配
            if (!user.getUserType().equals(userType)) {
                request.setAttribute("error", "用户类型不匹配，请选择正确的登录类型");
                request.getRequestDispatcher("/login.jsp").forward(request, response);
                return;
            }
            
            // 检查用户状态（除了管理员，其他用户禁用时都要校验）
            // 管理员（userType == 2）被禁用时仍然可以登录，普通用户和商户被禁用时不能登录
            if (user.getStatus() == 0 && userType != 2) {
                request.setAttribute("error", "账号已被禁用，请联系管理员");
                request.getRequestDispatcher("/login.jsp").forward(request, response);
                return;
            }
            
            // 验证密码
            User loginUser = userService.login(username, password);
            
            if (loginUser == null) {
                request.setAttribute("error", "用户名或密码错误");
                request.getRequestDispatcher("/login.jsp").forward(request, response);
                return;
            }
            
            HttpSession session = request.getSession();
            
            // 根据用户类型设置Session并跳转
            if (userType == 0) {
                // 客户端用户
                session.setAttribute("user", user);
                response.sendRedirect(request.getContextPath() + "/client/index");
            } else if (userType == 1) {
                // 商户
                session.setAttribute("merchant", user);
                response.sendRedirect(request.getContextPath() + "/merchant/index");
            } else if (userType == 2) {
                // 管理员
                session.setAttribute("admin", user);
                response.sendRedirect(request.getContextPath() + "/admin/index");
            } else {
                request.setAttribute("error", "无效的用户类型");
                request.getRequestDispatcher("/login.jsp").forward(request, response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error", "登录失败：" + e.getMessage());
            request.getRequestDispatcher("/login.jsp").forward(request, response);
        }
    }
}









